package com.zx.map.service.impl;

import com.zx.map.dao.TodoTaskDao;
import com.zx.map.dao.model.MerchantCertificateInfo;
import com.zx.map.dao.model.StoreInfo;
import com.zx.map.dao.model.TodoTask;
import com.zx.map.dao.model.TodoTaskExample;
import com.zx.map.dao.model.TodoTaskExample.Criteria;
import com.zx.map.service.*;
import com.zx.map.service.domain.TodoTaskDomain;
import com.zx.map.service.model.*;
import com.zx.map.utils.MyBeanUtils;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.service.proxy.MessageSendProxy;
import com.zx.platform.utils.*;
import com.zx.scp.utils.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 14-3-1 Time: 上午11:07 To
 * change this template use File | Settings | File Templates.
 */
@Component("todoTaskService")
public class TodoTaskServiceImpl implements TodoTaskService {

    @Autowired
    private TodoTaskDao dao;
    @Autowired
    private SettleCardInfoService settleCardInfoService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private SessionInfoService sessionInfoService;
    @Autowired
    private MerchantOfflineConfigInfoService merchantOfflineConfigInfoService;

    @Autowired
    private StoreInfoService storeInfoService ;
    /**
     * 得到所有数据列表
     */
    public List getAllList() throws DataAccessException {

        List<TodoTask> list = dao.getListByExample(null);
        List<TodoTaskModel> modelList = new ArrayList<TodoTaskModel>();
        for (TodoTask o : list) {
            TodoTaskModel temp = new TodoTaskModel();
            BeanUtils.copyProperties(o, temp);
            modelList.add(temp);
        }
        return modelList;

    }

    /**
     * 根据单Key查找Model
     */
    public TodoTaskModel getModelByKey(Integer key) throws DataAccessException {
        TodoTask o = dao.selectByPrimaryKey(key);
        TodoTaskModel model = new TodoTaskModel();
        BeanUtils.copyProperties(o, model);
        return model;
    }

    /**
     * 根据Model查找列表
     */
    public List getListByModel(TodoTaskModel model) throws DataAccessException {
        TodoTaskExample example = new TodoTaskExample();
        Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(model.getTaskType())) {
            criteria.andTaskTypeEqualTo(model.getTaskType());
        }
        if (StringUtils.isNotBlank(model.getTaskKey())) {
            criteria.andTaskKeyEqualTo(model.getTaskKey());
        }
        if (StringUtils.isNotBlank(model.getApproveStatus())) {
            criteria.andApproveStatusEqualTo(model.getApproveStatus());
        }
        List<TodoTask> list = dao.getListByExample(example);
        List<TodoTaskModel> modelList = new ArrayList<TodoTaskModel>();
        for (TodoTask o : list) {
            TodoTaskModel temp = new TodoTaskModel();
            BeanUtils.copyProperties(o, temp);
            modelList.add(temp);
        }
        return modelList;
    }

    /**
     * 新增
     */
    public Integer add(TodoTaskModel model) throws DataAccessException {
        TodoTask temp = new TodoTask();
        BeanUtils.copyProperties(model, temp);
        Integer key = dao.add(temp);
        return key;
    }

    /**
     * 修改
     */
    public Integer update(TodoTaskModel model) throws DataAccessException {
        TodoTask temp = new TodoTask();
        BeanUtils.copyProperties(model, temp);
        dao.update(temp);
        return model.getTaskId();
    }

    /**
     * 删除
     */
    public void delete(TodoTaskModel model) throws DataAccessException {
        TodoTask temp = new TodoTask();
        BeanUtils.copyProperties(model, temp);
        dao.delete(temp);
    }

    /**
     * 分页查询
     *
     * @param pageSize
     * @param pageNum
     * @param domain
     * @return
     * @throws DataAccessException
     */
    public Map getPageByDomain(int pageSize, int pageNum, TodoTaskDomain domain)
            throws DataAccessException {

        Map<String, Object> map = new HashMap<String, Object>();
        TodoTaskExample example = new TodoTaskExample();
        Criteria criteria = example.createCriteria();
        //增加申请人过滤条件edit by wenjw 2-15.6.15
        if (StringUtils.isNotBlank(domain.getApplyOperator()) && !"none".equals(domain.getApplyOperator())) {
            criteria.andApplyOperatorEqualTo(domain.getApplyOperator());
        }
        if (StringUtils.isNotBlank(domain.getTaskType())) {
            criteria.andTaskTypeEqualTo(domain.getTaskType());
        }
        if (domain.getBegindate() != null) {
            criteria.andCreateDateGreaterThanOrEqualTo(domain.getBegindate());
        }
        Date enddate = null;
        if (domain.getEnddate() != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            enddate = domain.getEnddate();
            String enddateStr = dateFormat.format(enddate);
            enddateStr = enddateStr + " 23:59:59";
            criteria.andCreateDateLessThanOrEqualTo(DateUtils.strToDate(enddateStr, "yyyy-MM-dd HH:mm:ss"));
        }
        if (StringUtils.isNotBlank(domain.getApproveStatus())) {
            criteria.andApproveStatusEqualTo(domain.getApproveStatus());
        }
        //排序add by wenjw 2015.6.2
        example.setOrderByClause("create_Date desc");
        int pageBegin = (pageNum - 1) * pageSize;
        List<TodoTask> list = dao
                .getPageByExample(pageSize, pageBegin, example);
        List<TodoTaskModel> menuModelList = new ArrayList<TodoTaskModel>();
        for (TodoTask o : list) {
            TodoTaskModel temp = new TodoTaskModel();
            BeanUtils.copyProperties(o, temp);
            menuModelList.add(temp);
        }
        int count = dao.countByExample(example);
        map.put("count", count);
        map.put("list", menuModelList);
        return map;
    }

    /**
     * 实际的新增todoTaskInfo的方法
     * <p/>
     * add by wenjw 2015.5.14
     *
     * @throws IOException
     */
    public Integer addTodoTask(Object object, TodoTaskModel model)
            throws DataAccessException, IOException {
        // 对象序列化
        String taskInfo = MyBeanUtils.beanToJson(object);
//        System.out.println(taskInfo);
        model.setTaskInfo(taskInfo);
        Integer taskId = this.add(model);
        
        return taskId;
    }

    /**
     * 实际的编辑todoTaskInfo的方法
     * <p/>
     * add by baojun.liu 2015.5.20
     *
     * @throws IOException
     */
    public Integer updateTodoTask(Object object, TodoTaskModel model)
            throws DataAccessException, IOException {
        // 对象序列化
        String taskInfo = MyBeanUtils.beanToJson(object);

        model.setTaskInfo(taskInfo);
        Integer taskId = this.update(model);
        return taskId;
    }

    /**
     * 统一的任务审核功能
     * 手工结算
     * 单笔结算、批量结算
     * 事务处理
     * edit by wenjw 2015.5.14
     *
     * @param model
     * @return
     * @throws DataAccessException
     * @throws ClassNotFoundException
     * @throws
     * @throws IOException
     */
    // 如果有事务,那么加入事务,没有的话新建一个(不写的情况下)
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer approveTaskAudit(TodoTaskModel model)
            throws DataAccessException, IOException, ClassNotFoundException {
        //查出任务
        Integer taskId = model.getTaskId();
        TodoTaskModel todoTaskModel = this.getModelByKey(taskId);
        //审核人员
        todoTaskModel.setApproveOperator(model.getApproveOperator());
        //审核日期
        todoTaskModel.setApproveDate(new Date());
        //审批状态
        todoTaskModel.setApproveStatus(model.getApproveStatus());
        //审批意见
        todoTaskModel.setApproveRemark(model.getApproveRemark());
        //备注
        todoTaskModel.setRemark(model.getRemark());

        this.update(todoTaskModel);
        String taskType = todoTaskModel.getTaskType();
        if ("1".equals(model.getApproveStatus())) {//审核通过，则数据落地
            if ("1".equals(taskType)) {//新增商户
                //新增
                MerchantInfoTodoTask merchantInfoTodoTask = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
                //客户信息表
                MerchantInfoModel merchantInfoModel = merchantInfoTodoTask.getMerchantInfoModel();
                //结算信息表
                SettleCardInfoModel settleCardInfoModel = merchantInfoTodoTask.getSettleCardInfoModel();
                 //商户证件信息关联表
                MerchantCertificateInfo record = merchantInfoTodoTask.getMerchantCertificateInfo();
                //新增商户
                merchantInfoModel.setCreateDate(todoTaskModel.getApproveDate());
                merchantInfoModel.setUpdateDate(new Date());
                String merchantId = null;
                
                if (StringUtils.isNotBlank(merchantInfoModel.getMerchantId())){ //如果merchantId不为空的 进行更新操作 app用户注册 进行数据更新操作
                    merchantId = merchantInfoModel.getMerchantId();
                    merchantInfoModel.setStatus("0");//0--表示用户状态正常
                    merchantInfoService.update(merchantInfoModel);
                } else {
                    merchantInfoModel.setTradePassword(PmpUtils.encoderByMD5(MD5Util
                            .getMD5Str(merchantInfoModel.getTradePassword())));
                    merchantInfoModel.setSysPassword(PmpUtils.encoderByMD5(MD5Util
                            .getMD5Str(merchantInfoModel.getSysPassword())));
                    merchantInfoModel.setStatus("0");//0--表示用户状态正常
                    merchantId = merchantInfoService.add(merchantInfoModel);
                }
                settleCardInfoModel.setSubjectId(merchantId);
                settleCardInfoModel.setSubjectType("1");//主体为商户
                //新增结算信息表
                settleCardInfoService.add(settleCardInfoModel);
                //新增商户证件信息关联表
                record.setMerchantId(merchantId);
                merchantInfoService.addMerchantCertificateInfo(record);
                StoreInfo storeInfo = storeInfoService.find(merchantInfoModel.getMerchantId());
                storeInfo.setStoreStatus(0);
                storeInfoService.update(storeInfo);
                // 需要将前端用户登陆信息删除 方便用户重新登陆
                sessionInfoService.delete(merchantInfoModel.getSysAccount());
                //发送通知短信
                MessageSendProxy.getMessageResponse(MobileCommonHelper.MESSAGETYPE_USERREVIEW, merchantInfoModel.getSysAccount());

            }  else if ("6".equals(taskType)) {//银行更换
                //银行更换
                SettleCardInfoModel settleCardInfoModel = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),SettleCardInfoModel.class);
                String settleIdStr = todoTaskModel.getTaskKey();
                Integer settleId = Integer.valueOf(settleIdStr);
                SettleCardInfoModel SettleCardInfoModel = settleCardInfoService.getModelByKey(settleId);
                SettleCardInfoModel.setDepositBank(settleCardInfoModel.getDepositBank());
                SettleCardInfoModel.setDepositBankbranch(settleCardInfoModel.getDepositBankbranch());
                SettleCardInfoModel.setBankAccount(settleCardInfoModel.getBankAccount());
                SettleCardInfoModel.setBankUsrname(settleCardInfoModel.getBankUsrname());

                String taskOperatorType = todoTaskModel.getTaskOperatorType();
                if ("2".equals(taskOperatorType)) {//修改\应该都是修改
                    settleCardInfoService.update(SettleCardInfoModel);
                } else {
                    settleCardInfoService.add(SettleCardInfoModel);
                }
            } else if ("8".equals(taskType)) {//二维码申请
                //新增二维码申请
                MerchantOfflineConfigInfoModel merchantOfflineConfigInfoModel =MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantOfflineConfigInfoModel.class);
                merchantOfflineConfigInfoModel.setCreateDate(new Date());
                merchantOfflineConfigInfoModel.setOfflinePayUrl(PropertyUtil.getValue("mobile_base_url")+"/mobile/offline/index?offLineMerchantCode=" + merchantOfflineConfigInfoModel.getMerchantId() + "&mCode=" + merchantOfflineConfigInfoModel.getOfflinePayId()+"&appId=5202991");
                merchantOfflineConfigInfoService.add(merchantOfflineConfigInfoModel);
            }
        } else if ("2".equals(model.getApproveStatus())) {//审核拒绝，则更新数据
            if ("1".equals(taskType)) {//新增商户
                //新增
                MerchantInfoTodoTask merchantInfoTodoTask = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
                //客户信息表
                MerchantInfoModel merchantInfoModel = merchantInfoTodoTask.getMerchantInfoModel();
                if (StringUtils.isNotBlank(merchantInfoModel.getMerchantId())) //如果merchantId不为空的 进行更新操作 app用户注册 进行数据更新操作
                {
                    merchantInfoModel.setStatus("2");//0--表示绑卡正常  1--正在绑卡未审核通过  2--未提交绑卡申请  3--审核拒绝  4--锁定
                    merchantInfoService.update(merchantInfoModel);
                    StoreInfo storeInfo = storeInfoService.find(merchantInfoModel.getMerchantId());
                    storeInfo.setStoreStatus(2);
                    storeInfoService.update(storeInfo);
                }
            }
        }
        return model.getTaskId();
    }

    /**
     * 获得待审核笔数
     */
    public Integer getCountBytaskType(String taskType, String approveStatus)
            throws DataAccessException {
        TodoTaskExample example = new TodoTaskExample();
        Criteria criteria = example.createCriteria();
        criteria.andTaskTypeEqualTo(taskType);
        criteria.andApproveStatusEqualTo(approveStatus);

        return dao.countByExample(example);
    }
}
